package com.hangwei.paperless;

import android.Manifest;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.hangwei.paperless.model.bean.Login;
import com.hangwei.paperless.model.bean.TokenInfo;
import com.hangwei.paperless.model.bean.UserInfo;
import com.hangwei.paperless.presenter.StaticPresenter;
import com.hangwei.paperless.widget.CardLoginPop;
import com.twelve.all.base.NFCApp;
import com.twelve.all.net.CallBack;
import com.twelve.all.nfc.BasicActivity;
import com.twelve.all.nfc.Constants;
import com.twelve.all.nfc.MCReader;
import com.twelve.all.nfc.PreferencesUtil;
import com.twelve.all.nfc.Utils;
import com.twelve.all.utils.LoadingDialog;
import com.twelve.all.utils.LogUtil;
import com.twelve.all.utils.MD5Util;
import com.twelve.all.utils.PackageUtil;
import com.twelve.all.utils.SPKey;
import com.twelve.all.utils.SPUtil;
import com.twelve.all.utils.ToastUtil;

import java.util.Date;

/**
 * Created by 张龙臣 on 2020/10/11.
 */

public class LoginActivity extends BasicActivity implements View.OnClickListener {

    private EditText mEtPassword;
    private EditText mEtUserName;
    private LoadingDialog mLoadingDialog;
    private CardLoginPop mCardLoginPop;
    private boolean mCanCard = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        TextView tvLoginByCard = (TextView) findViewById(R.id.tvLoginByCard);
        TextView tvLogin = (TextView) findViewById(R.id.tvLogin);
        mEtPassword = (EditText) findViewById(R.id.etPassword);
        mEtUserName = (EditText) findViewById(R.id.etUserName);
        TextView tvVersion = (TextView) findViewById(R.id.tvVersion);
        tvVersion.setText(PackageUtil.getLocalVersionName(this));
//        SPUtil.setString(SPKey.Account.TOKEN,null);
        tvLogin.setOnClickListener(this);
//        tvLoginByCard.setOnClickListener(this);
//        tvLoginByCard.setVisibility(View.GONE);
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
                1);
        tvLoginByCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (NFCApp.hasWritePermissionToExternalStorage(LoginActivity.this)) {
                    NFCApp.setUseAsEditorOnly(NFCApp.useAsEditorOnly());
                    runStartUpNode(StartUpNode.FirstUseDialog);
//                    startActivity(new Intent(LoginActivity.this,CardLoginActivity.class));
                    if (mCardLoginPop == null)
                        mCardLoginPop = new CardLoginPop(LoginActivity.this) {
                            @Override
                            public void onDismiss() {
                                mCanCard = false;
                            }
                        };
                    if (!mCardLoginPop.isShowing())
                        mCardLoginPop.showAtLocation(getWindow().getDecorView(), Gravity.CENTER, 0, 0);
                    mCanCard = true;
                } else {
                    ActivityCompat.requestPermissions(LoginActivity.this,
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
                            1);
                }
            }
        });

        String loginName = SPUtil.getString(SPKey.Account.LOGIN_NAME);
        String password = SPUtil.getString(SPKey.Account.PASSWORD);
        if (!TextUtils.isEmpty(loginName)) mEtUserName.setText(loginName);
//        if (Tools.isDebug() && !TextUtils.isEmpty(password))
//            mEtPassword.setText(password);

        mEtPassword.setText("test2");
        mEtUserName.setText("test2");
//        doLogin();
        mEtUserName.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_NEXT ||
                        (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    mEtPassword.setFocusable(true);
                    mEtPassword.setFocusableInTouchMode(true);
                    mEtPassword.requestFocus();
                    return true;
                }
                return false;
            }
        });
        mEtPassword.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND ||
                        (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    doLogin();
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.tvLogin:
                doLogin();
                break;
        }

    }

    private void doLogin() {
        final String username = mEtUserName.getText().toString().trim();
        final String password = mEtPassword.getText().toString().trim();
        if (TextUtils.isEmpty(username)) {
            ToastUtil.showCenterToast("请输入用户名！");
            return;
        }
        if (TextUtils.isEmpty(password)) {
            ToastUtil.showCenterToast("请输入密码！");
            return;
        }
        mLoadingDialog = new LoadingDialog(this);
        mLoadingDialog.show();
        StaticPresenter.doLoginPad(username, password, new CallBack<Login>() {
            @Override
            public void onCompleted(Login login) {
                SPUtil.setString(SPKey.Account.PASSWORD, password);
                SPUtil.setString(SPKey.Account.LOGIN_NAME, username);
                SPUtil.setString(SPKey.Account.APP_ID, login.appid);
                int num = (int) (Math.random() * 103 + 1) * 31;
                long time = new Date().getTime();
                String sign = MD5Util.getMD5("appid=" + login.appid + "&" +
                        "nonce=" + num + "&" +
                        "timestamp=" + time + "&" +
                        "appkey=" + login.appkey);
                getToken(login, time, num + "", sign);
            }

            @Override
            public void onError() {
                if (mLoadingDialog != null && mLoadingDialog.isShowing())
                    mLoadingDialog.dismiss();
            }
        });
    }

    private void getToken(final Login login, long time, String num, String sign) {
        StaticPresenter.getToken(login.appid, time, num, sign, new CallBack<TokenInfo>() {
            @Override
            public void onCompleted(TokenInfo tokenInfo) {
                SPUtil.setString(SPKey.Account.TOKEN, tokenInfo.token);
                getUserInfo(login.userId);
            }

            @Override
            public void onError() {
                if (mLoadingDialog != null && mLoadingDialog.isShowing())
                    mLoadingDialog.dismiss();
            }
        });
    }

    private void getUserInfo(final String userId) {
        StaticPresenter.getUserInfo(userId, new CallBack<UserInfo>() {
            @Override
            public void onCompleted(UserInfo userInfo) {
                if (mLoadingDialog != null && mLoadingDialog.isShowing())
                    mLoadingDialog.dismiss();
                SPUtil.setString(SPKey.Account.USER_ID, userInfo.userId);
                SPUtil.setString(SPKey.Account.USER_HEAD, userInfo.avatar);
                SPUtil.setString(SPKey.Account.UNIT_ID, userInfo.unitid);
                SPUtil.setString(SPKey.Account.UNIT_NAME, userInfo.unitname);
                SPUtil.setString(SPKey.Account.USER_NAME, userInfo.username);
                SPUtil.setString(SPKey.Account.SIGN_PIC, userInfo.signature);
                if (userInfo.stamp != null && userInfo.stamp.size() > 0) {
                    SPUtil.setString(SPKey.STAMP_ID, userInfo.stamp.get(0).stampId);
                }
                App.stamps = userInfo.stamp;
                App.docrole = userInfo.docrole;
                startActivity(new Intent(LoginActivity.this, HomeActivity.class));
                mCanCard = false;
                finish();
            }

            @Override
            public void onError() {
                if (mLoadingDialog != null && mLoadingDialog.isShowing())
                    mLoadingDialog.dismiss();
            }
        });
    }

    @Override
    public void onNewIntent(Intent intent) {
        Log.i(this.getClass().getSimpleName(), "onNewIntent: -------------------------");
        if (mCanCard && NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
            Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            tag = MCReader.patchTag(tag);
//            setTag(tag);
//            Utils.logUid(Utils.byte2Hex(tag.getId()));

            boolean isCopyUID = PreferencesUtil.getPreferences().getBoolean(
                    Constants.AutoCopyUID, false);
            if (isCopyUID) {
                int format = PreferencesUtil.getPreferences().getInt(
                        Constants.UIDFormat, 0);
                String fmtUID = Utils.byte2FmtString(tag.getId(), format);
            } else {
                // Show Toast message with UID.
                String msg = Utils.byte2Hex(tag.getId());
                LogUtil.i("byte2Hex:"+msg);
                    StaticPresenter.doLoginPadByCard(msg, new CallBack<Login>() {
                        @Override
                        public void onCompleted(Login login) {
                            SPUtil.setString(SPKey.Account.APP_ID, login.appid);
                            int num = (int) (Math.random() * 103 + 1) * 31;
                            long time = new Date().getTime();
                            String sign = MD5Util.getMD5("appid=" + login.appid + "&" +
                                    "nonce=" + num + "&" +
                                    "timestamp=" + time + "&" +
                                    "appkey=" + login.appkey);
                            getToken(login, time, num + "", sign);
                            if (mCardLoginPop != null && mCardLoginPop.isShowing()) {
                                mCardLoginPop.dismiss();
                            }
                        }

                        @Override
                        public void onError() {
                            if (mLoadingDialog != null && mLoadingDialog.isShowing())
                                mLoadingDialog.dismiss();
                            if (mCardLoginPop != null && mCardLoginPop.isShowing()) {
                                mCardLoginPop.dismiss();
                            }
                        }
                    });
            }
        }
    }
//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (KeyEvent.KEYCODE_BACK == keyCode)
//           if (mCardLoginPop!=null&&mCardLoginPop.isShowing()){
//               mCardLoginPop.dismiss();
//               return true;
//           }
//        return super.onKeyDown(keyCode, event);
//    }

}